<!DOCTYPE html>
<html>
<head>
    <title>与供应商聊天</title>
    <link rel="icon" href="/uploads/logo.png" type="image/x-icon"/>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

    <!--公共样式整合 -->
    <style>
        .form-label {
            font-weight: 500;
            color: #4b5563;
        }
        .form-input {
            transition: all 0.2s ease-in-out;
        }
        .form-input:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        main {
            display: flex;
            min-height: calc(100vh - 50px - 50px);
            width: 100%;
        }

        .sidebar {
            width: 200px;
            background-color: #fff;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }

        /* 右侧聊天区域布局为垂直方向 */
        .chat-panel {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-width: 0;
        }
        .sidebar nav {
            flex-grow: 1;
        }

        .content-area {
            flex: 1;
            padding: 2rem;
            background-color: #f7fafc;
        }

        @media (max-width: 640px) {
            .sidebar {
                display: none;
            }
            .content-area {
                padding: 1rem;
            }
        }

        /* 聊天列表按钮样式优化 */
        .contact-btn {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem;
            border-bottom: 1px solid #f3f4f6;
            font-weight: 500;
            color: #374151;
            transition: background-color 0.2s;
            text-decoration: none;
        }

        .contact-btn:hover {
            background-color: #f9fafb;
        }

        .contact-btn.active {
            background-color: #e0f2fe;
            color: #2563eb;
        }

        .contact-btn .icon {
            margin-right: 0.5rem;
            color: #3b82f6;
        }

        .unread-count {
            background: #dc2626;
            color: white;
            border-radius: 9999px;
            padding: 2px 6px;
            font-size: 12px;
        }
        /* 聊天输入框固定在 chat-panel 内部底部 */
        .chat-input {
            height: 60px;
            background-color: #fff;
            border-top: 1px solid #ddd;
            display: flex;
            align-items: center;
            padding: 0 1rem;
        }

        .chat-input form {
            display: flex;
            width: 100%;
            gap: 0.5rem;
        }

        .chat-input input[type="text"] {
            flex: 1;
            padding: 0.5rem 1rem;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .chat-input button {
            padding: 0.5rem 1.25rem;
            background-color: #3b82f6;
            color: white;
            border-radius: 5px;
            border: none;
        }

        /* 新增：调整“+”按钮样式 */
        .chat-input .orders-btn {
            padding: 0.5rem;
            background-color: #10b981;
            color: white;
            border-radius: 5px;
            border: none;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .chat-input .orders-btn:hover {
            background-color: #059669;
        }

        /* 聊天内容区域添加滚动条 */
        .chat-messages {
            margin-bottom: 5rem; /* 保留足够空间避免被输入框遮挡 */
            max-height: calc(100vh - 220px); /* 调整最大高度，适应新的 main 高度 */
            overflow-y: auto; /* 添加垂直滚动条 */
            padding-right: 0.5rem; /* 防止滚动条遮挡内容 */
        }

        /* 聊天内容区域滚动条美化 */
        .chat-messages::-webkit-scrollbar {
            width: 8px;
        }
        .chat-messages::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        .chat-messages::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .chat-header {
            margin-bottom: 1rem;
        }

        .message {
            margin-bottom: 1rem;
            display: flex;
        }

        .message.sent {
            justify-content: flex-end;
        }

        .message.received {
            justify-content: flex-start;
        }

        .message-content {
            max-width: 60%;
            background-color: #e0f2fe;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            word-break: break-word;
        }
        .message.sent .message-content {
            background-color: #3b82f6;
            color: white;
        }


        #ordersModal .bg-white {
            margin: 0 auto; /* 水平居中 */
            align-items: center; /* 垂直居中 */

        }
    </style>
</head>
<body>
<th:block th:replace="~{/header.html}"></th:block>
<main class="flex min-h-[calc(100vh-50px-50px)]">
    <th:block th:replace="~{/buyer/sidebar.html}"></th:block>
    <!-- 聊天侧边栏 -->
    <div class="sidebar w-1/5 bg-white shadow flex flex-col">
        <h2 class="text-center text-xl font-semibold text-gray-800 py-4 border-b">消息通知列表</h2>
        <nav class="flex-grow overflow-y-auto">
            <ul>
                <li th:each="contact : ${contacts}">
                    <a th:href="@{/buyer/message/chat/{id}(id=${contact.id})}"
                       th:class="'contact-btn' + (${contact.id} == ${selectedContactId} ? ' active' : '')">
                                <span>
                                    <svg xmlns="http://www.w3.org/2000/svg" class="icon inline-block w-5 h-5" fill="none"
                                         viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                              d="M17 8h2a2 2 0 012 2v9l-4-4H7a2 2 0 01-2-2V6a2 2 0 012-2h8" />
                                    </svg>
                                    <span th:text="${contact.username}"></span>
                                </span>
                        <span th:if="${contact.unreadCount > 0}" class="unread-count" th:text="${contact.unreadCount}"></span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
    <!--  聊天内容主体 -->
    <div class="chat-panel flex-grow flex flex-col bg-gray-50 p-6">
        <div class="chat-header mb-4">
            <h3 th:text="'与 ' + ${contact.username} + ' 聊天'"></h3>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div th:each="message : ${messages}"
                 th:classappend="${message.senderId == currentUserId} ? 'message sent' : 'message received'">
                <div class="message-content">
                    <span th:text="${message.content}"></span>
                    <br>
                    <small th:text="${#temporals.format(message.createTime, 'yyyy-MM-dd HH:mm')}"></small>
                </div>
            </div>
        </div>
        <div class="chat-input">
            <form th:action="@{/buyer/message/send}" method="post" class="flex w-full gap-2">
                <button type="button" onclick="showOrdersModal()" class="orders-btn">+</button>
                <input type="hidden" name="receiverId" th:value="${contact.id}">
                <input type="hidden" name="senderId" th:value="${currentUserId}">
                <input type="text" name="content" placeholder="输入消息..." required class="flex-1 border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring focus:border-blue-300">
                <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">发送</button>
            </form>
        </div>

        <!-- 订单模态框 -->
        <div id="ordersModal" class="fixed inset-0 bg-black bg-opacity-40 z-50 hidden flex items-center justify-center">
            <div class="bg-white rounded-xl shadow-lg w-full max-w-3xl p-6">
                <div class="flex justify-between items-center border-b pb-4 mb-4">
                    <h2 class="text-xl font-bold text-green-700">我的订单</h2>
                    <button class="text-gray-500 hover:text-black text-2xl font-bold" onclick="closeOrdersModal()">×</button>
                </div>
                <table class="w-full border text-sm text-left">
                    <thead class="bg-green-600 text-white">
                    <tr>
                        <th class="px-4 py-2">订单编号</th>
                        <th class="px-4 py-2">总金额</th>
                        <th class="px-4 py-2">状态</th>
                        <th class="px-4 py-2">创建时间</th>
                    </tr>
                    </thead>
                    <tbody id="ordersTableBody" class="bg-white divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>
<!-- 公共底部 -->
<th:block th:replace="~{/footer.html}"></th:block>

<script th:inline="javascript">
    var stompClient = null;
    var senderId = [[${currentUserId}]];
    var receiverId = [[${contact.id}]];

    // 将订单数据嵌入 JavaScript 变量
    var orders = [
        /*[# th:each="order : ${orders}"]*/
        {
            orderNo: /*[[${order.orderNo}]]*/ '未知',
            totalAmount: /*[[${order.totalAmount != null ? order.totalAmount : 0.0}]]*/ 0.0,
            status: /*[[${order.status}]]*/ '未知',
            createTime: /*[[${order.createTime != null ? #dates.format(order.createTime, 'yyyy-MM-dd HH:mm:ss') : '未知'}]]*/ '未知'
        },
        /*[/]*/
    ];

    // 确保页面加载时不自动调用 showOrdersModal
    function connect() {
        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/messages/' + senderId, function(message) {
                var payload = JSON.parse(message.body);
                showMessage(payload.content, payload.senderId == senderId);
            });
        });
    }

    function showMessage(content, isSent) {
        var messageDiv = document.createElement('div');
        messageDiv.className = isSent ? 'message sent' : 'message received';
        messageDiv.innerHTML = '<div class="message-content">' + content + '<br><small>' + new Date().toLocaleString() + '</small></div>';
        document.getElementById('chatMessages').appendChild(messageDiv);
        document.getElementById('chatMessages').scrollTop = document.getElementById('chatMessages').scrollHeight;
    }

    // 显示订单模态框，仅通过“+”按钮触发
    function showOrdersModal() {
        var modal = document.getElementById('ordersModal');
        var tbody = document.getElementById('ordersTableBody');
        tbody.innerHTML = ''; // 清空表格内容

        if (orders.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4">暂无订单</td></tr>';
        } else {
            orders.forEach(order => {
                var row = document.createElement('tr');
                row.innerHTML = `
                    <td>${order.orderNo || '未知'}</td>
                    <td>${order.totalAmount ? order.totalAmount.toFixed(2) : '0.00'}</td>
                    <td>${order.status || '未知'}</td>
                    <td>${order.createTime || '未知'}</td>
                `;
                tbody.appendChild(row);
            });
        }
        modal.style.display = 'block';
    }

    // 关闭订单模态框
    function closeOrdersModal() {
        var modal = document.getElementById('ordersModal');
        modal.style.display = 'none';
    }

    // 点击模态框外部关闭模态框
    window.onclick = function(event) {
        var modal = document.getElementById('ordersModal');
        if (event.target === modal) {
            modal.style.display = 'hidden';
        }
    }

    // 页面加载时仅初始化 WebSocket 连接，不自动调用 showOrdersModal
    window.onload = function() {
        connect();
    };
</script>
</body>
</html>